package cn.com.jinhao.provider.user.controller;

import cn.com.jinhao.hotline.commons.base.constant.SystemConstant;
import cn.com.jinhao.hotline.commons.controller.BaseController;
import cn.com.jinhao.hotline.commons.util.RestResponse;
import cn.com.jinhao.provider.user.entity.Role;
import cn.com.jinhao.provider.user.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * hotline-spring-cloud
 * <p>Description: </p>
 *
 * @author ShaneMew
 * @version 1.0
 * @date 2019/12/26
 * @since 2019-12-26
 */
@RestController
@RequestMapping("roles")
@Api(tags = {"角色服务"})
public class RoleController extends BaseController {
    @Resource
    private RoleService roleService;

    @ApiOperation(value = "查询角色", notes = "根据角色编码查询角色信息")
    @ApiImplicitParam(name = "code", value = "角色编码", required = true, dataType = "String", paramType = "path")
    @GetMapping
    public RestResponse<Object> queryUser(@RequestParam String code) throws Exception {
        return  this.checkExist(roleService.queryByCode(code));
    }

    @ApiOperation(value = "创建角色", notes = "根据角色对象创建角色")
    @PostMapping
    public RestResponse<Role> addRole(@ApiParam(name = "role", value = "角色信息", required = true) @RequestBody Role role) throws Exception {
        return this.executeMethod(role, SystemConstant.DataOperType.DATA_OPER_TYPE_ADD.getValue());
    }

    @ApiOperation(value = "更新角色", notes = "更新角色信息")
    @PutMapping
    public RestResponse<Role> updateUser(@ApiParam(name = "role", value = "角色信息", required = true) @RequestBody Role role) throws Exception {
        if (StringUtils.isBlank(role.getCode())) {
            throw new IllegalArgumentException("角色编码不能为空");
        }
        return this.executeMethod(role, SystemConstant.DataOperType.DATA_OPER_TYPE_UPDATE.getValue());
    }

    @ApiOperation(value = "删除角色", notes = "根据角色编码删除角色信息")
    @DeleteMapping
    public RestResponse<Role> deleteUser(@ApiParam(name = "code", value = "角色编码", required = true)@RequestParam String code) throws Exception {
        return this.executeMethod(code, SystemConstant.DataOperType.DATA_OPER_TYPE_DEL.getValue());
    }

    private RestResponse<Role> executeMethod(Object obj, int methodType) throws Exception {
        switch (Objects.requireNonNull(SystemConstant.DataOperType.getByValue(methodType))) {
            case DATA_OPER_TYPE_UPDATE:
                roleService.update((Role) obj);
                break;
            case DATA_OPER_TYPE_DEL:
                roleService.delete(obj.toString());
                break;
            default:
                roleService.add((Role) obj);
                break;
        }
        return new RestResponse<>(null);
    }
}
